﻿using AutoMapper;
using MaterialTypeRecognition.Shell.Exceptions;
using MaterialTypeRecognition.Shell.UnitOfWork;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MaterialTypeRecognition.Shell.Uers
{
    public class UserService : IUserService
    {
        private readonly IUserRepository _repository;

        private readonly IMapper _mapper;

        private readonly IUnitOfWork _unit;

        public UserService(IUserRepository repository, IMapper mapper, IUnitOfWork unitOfWork)
        {
            _repository = repository;
            _mapper = mapper;
            _unit = unitOfWork;
        }

        public async Task RegisterAsync(UserDto userDto)
        {
            if (await _repository.ExistsAsync(user => user.Key == userDto.Key))
            {
                throw new UserAlreadyExistsException();
            }

            var user = _mapper.Map<User>(userDto);

            await _repository.InsertAsync(user);
            await _unit.SaveChangesAsync();
        }

        public async Task UnregisterAsnyc(string key)
        {
            var user = await _repository.GetFirstOrDefaultAsync(user => user.Key == key, null, null, false, false);

            if (user is null)
            {
                throw new UserNotExistsException();
            }

            _repository.Delete(user);
            await _unit.SaveChangesAsync();
        }

        public async Task<List<UserInfoDto>> GetAllAsync()
        {
            var users = await _repository.GetAllAsync();
            var userInfos = _mapper.Map<List<User>, List<UserInfoDto>>(users.ToList());

            return userInfos;
        }
    }
}
